const db = wx.cloud.database()

let userInfo = {}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId:String,
    blog:Object
  },

  externalClasses:[
    "iconfont",
    "icon-pinglun",
    "icon-fenxiang"
  ],

  /**
   * 组件的初始数据
   */
  data: {
    // 登录组件是否显示
    isLoginShow:false,
    // 底部弹出层是否显示
    isModelShow:false,
    content:'',
    footerBottom:0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment(){
      this.setData({
        isLoginShow:true
      })
    },

    getUserInfoSuccess(e){
      userInfo = e.detail
      // console.log(e);
      this.setData({
        isModelShow:true
      })
    },

    getUserInfoFail(){
      wx.showModal({
        title:"用户授权后才可以评论"
      })
    },

    onFocus(e){
      this.setData({
        footerBottom:e.detail.height
      })
    },
    onBlur(){
      this.setData({
        footerBottom:0
      })
    },
    // 监听评论框输入事件
    onInput(e){
      this.setData({
        content:e.detail.value
      })
    },
    onSend(){
      // 推送订阅消息
      const templateId = 'eE1PGEdy4PNqt6cHAnmfwjrTS5g8BvHPkkKehkCj718'
      wx.requestSubscribeMessage({
        tmplIds: [templateId],
        success:(res)=>{
          if(res[templateId] == 'accept'){
            wx.showToast({
              title: '订阅成功',
            })
          }else{
            wx.showToast({
              title: '订阅失败',
            })
          }
        },
        fail:(err) => {
          console.error(err)
        }
      })


      let content = this.data.content
      if(content.trim() == ''){
        wx.showModal({
          title:"评论内容不能为空"
        })
        return
      }

      wx.showLoading({
        title: '发布中',
        mask:true
      })

      db.collection('blog-comment').add({
        data:{
          content,
          blogId:this.properties.blogId,
          createTime:db.serverDate(),
          nickName:userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then(res => {
        wx.cloud.callFunction({
            name:'sendMessage',
            data:{
              content,
              blogId:this.properties.blogId
            }
          }).then(res =>{
            console.log(res);
          })
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '评论成功',
      })
      this.setData({
        isModelShow:false,
        content:''
      })      
      // 父元素刷新评论
      this.triggerEvent('refreshCommentList')
    },
  }
})
